import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const foodsStore = createSlice({
  name: 'foods',
  initialState: {
    // 商品列表
    foodsList: [],
    // 激活菜单项下标值
    activeIndex: 0,
    // 购物车列表
    cartList: []
  },
  reducers: {
    // 修改商品列表
    setFoodsList (state, action) {
      state.foodsList = action.payload
    },
    // 修改激活菜单项下标值
    changeActiveIndex (state, action) {
      state.activeIndex = action.payload
    },
    // 添加购物车
    addCart (state, action) {
      // 判断购物车里面是否已经存在该商品SKU
      const item = state.cartList.find(item => item.id === action.payload.id)
      if (item) {
        item.count++
      } else {
        state.cartList.push(action.payload)
      }
    },
    // count 增
    increCount (state, action) {
      const item = state.cartList.find(item => item.id === action.payload.id)
      item.count++
    },
    // count 减
    decreCount (state, action) {
      const item = state.cartList.find(item => item.id === action.payload.id)
      if (item.count === 1) {
        state.cartList = state.cartList.filter(item => item.id !== action.payload.id)
      }
      item.count--
    },
    // 清空购物车
    clearCart (state) {
      state.cartList = []
    }
  }
})
// 异步获取部分
const { setFoodsList, changeActiveIndex, addCart, increCount, decreCount, clearCart } = foodsStore.actions
const fetchFoodsList = () => {
  return async (dispatch) => {
    const res = await axios.get('http://localhost:3004/takeaway')
    dispatch(setFoodsList(res.data))
  }
}

export { fetchFoodsList, changeActiveIndex, addCart, increCount, decreCount, clearCart }
const reducer = foodsStore.reducer
export default reducer